# 回溯

# 冲突检测
# nextX 水平位置 nextY 垂直位置
# 检查下一个皇后与当前皇后是否x相同或者对角线上，冲突返回True
def conflict(state, nextX):
    nextY = len(state)
    for i in range(nextY):
        # 同一列 或 对角线
        if abs(state[i] - nextX) in (0, nextY - i):
            return True
    return False


def queens(num=8, state=()):
    for pos in range(num):
        if not conflict(state, pos):
            if len(state) == num - 1:
                yield (pos,)
            else:
                for result in queens(num, state + (pos,)):
                    yield (pos,) + result


print(list(queens(3)))
print(list(queens(4)))
#
for solution in queens(8):
    print(solution)


def prettyprint(solution):
    def line(pos, length=len(solution)):
        return '. ' * (pos) + 'X ' + '. ' * (length - pos - 1)

    for pos in solution:
        print(line(pos))


import random

prettyprint(random.choice(list(queens(8))))  #
